<template>
  <div ref="box">
    <div id="chartTwo" style="width:100%;"></div>
    <!-- noData -->
    <div v-if="noData" class="no-data">暂无数据</div>
  </div>
</template>

<script>
import Ecolors from "@/utils/chartsColors";
import { resize } from "@/utils/utils";
export default {
  mixins: [resize],
  props: {
    info: {
      type: Object,
    },
    offsetHeight: {
      type: Number,
    },
  },
  data() {
    return {
      chartTwo: null,
      currentLegendName: "", // 当前选中图例
      noData: false,
    };
  },
  methods: {
    // 领域变化分析
    getchartTwoData() {
      this.chartTwo.showLoading({
        text: "loading",
        color: "#0b0a2b",
        textColor: "#0b0a2b",
        maskColor: "#fff",
        zlevel: 0,
      });

      // 展示最近10年
      this.$post(this.$Url.team.analysis, {
        musts: {
          date_sort: "1",
          "in2id.id": this.info.key,
        },
        aggs: {
          size: "10",
          field: "ipc_kind",
          type: "base",
          subAggs: {
            interval: "YEAR",
            format: "yyyy-MM-dd",
            field: "ad",
            type: "date",
          },
        },
      })
        .then((res) => {
          let data = res.data;
          if (data && data.length > 0) {
            let d = [];
            let yearArr = [];

            data.forEach((v) => {
              let buckets =
                (v["date_histogram#AGG"] &&
                  v["date_histogram#AGG"]["buckets"]) ||
                [];
              if (buckets.length > 0) {
                buckets.forEach((b) => {
                  yearArr.push(b["key_as_string"]);
                });
              }
            });

            yearArr = Array.from(new Set(yearArr));

            data.forEach((v) => {
              let buckets =
                (v["date_histogram#AGG"] &&
                  v["date_histogram#AGG"]["buckets"]) ||
                [];
              if (buckets.length > 0) {
                for (let i in yearArr) {
                  for (let j in buckets) {
                    let doc_count = 0;
                    if (yearArr[i] === buckets[j]["key_as_string"]) {
                      doc_count = buckets[j]["doc_count"];
                    }
                    d.push([yearArr[i], doc_count, v.key]);
                    break;
                  }
                }
              }
            });

            // 如果年时间数量为1，则拓展到年底，否则无法正常展示河流图
            if (yearArr.length === 1) {
              let addArr = [];
              d.forEach((v) => {
                let year = v[0].split("-")[0];
                addArr.push([`${year}-12-31`, v[1], v[2]]);
              });
              d.push(...addArr);
            }
            this.renderchartTwo(d);
          } else {
            this.noData = true;
            this.chartTwo.hideLoading();
          }
        })
        .catch((err) => {});
    },
    renderchartTwo(data) {
      let option = {
        backgroundColor: "#fff",
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "line",
            snap: true,
            lineStyle: {
              color: "rgba(0,0,0,0.2)",
              width: 1,
              type: "solid",
            },
          },
          formatter: function(x) {
            let param = x;
            let str = "";
            for (let i = 0; i < param.length; i++) {
              let paramI = param[i];
              if (paramI.data[2].length > 40) {
                str += `${paramI.data[2].substr(0, 40)}...：${
                  paramI.data[1]
                }<br/>`;
              } else {
                str += `${paramI.data[2]}：${paramI.data[1]}<br/>`;
              }
            }
            return str;
          },
        },
        legend: {
          type: "scroll",
          // left: '5%',
          right: "20",
          orient: "horizontal",
          icon: "roundRect",
          itemWidth: 20,
          itemHeight: 10,
          textStyle: {
            padding: [0, 10],
          },
          formatter: (label) => {
            return label;
          },
        },
        color: Ecolors.color,
        singleAxis: {
          top: 50,
          bottom: 50,
          axisTick: {},
          axisLabel: {
            textStyle: {
              color: "#9e9e9e",
            },
          },
          type: "time",
          axisPointer: {
            animation: true,
            label: {
              show: true,
              color: "#9e9e9e",
              // backgroundColor: ''
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
              opacity: 0.2,
            },
          },
          axisLine: {
            lineStyle: {
              color: "#f0f1f3",
              width: 2,
            },
          },
        },
        series: [
          {
            type: "themeRiver",
            avoidLabelOverlap: true,
            data,
            itemStyle: {
              normal: {
                borderWidth: 2,
                borderColor: "#fff",
              },
            },
            label: {
              show: false,
              position: "outer",
              alignTo: "labelLine",
              distanceToLabelLine: 5,
              formatter: (params) => {
                let str = "";
                if (params.name.length > 10) {
                  str += `{nameStyle|${params.name.substring(0, 10)}...}`;
                } else {
                  str += `{nameStyle|${params.name}}`;
                }
                // console.log(params)
                // str += `{nameStyle|${params.percent}%}`
                str = `{nameStyle|${params.percent}%}`;
                return str;
              },
              rich: {
                icon: {},
                nameStyle: {
                  fontSize: 12,
                  color: "#86899e",
                },
              },
            },
          },
        ],
      };
      this.chartTwo.hideLoading();
      this.chartTwo.setOption(option, true);
      // 图例反选
      this.chartTwo.on("legendselectchanged", (obj) => {
        const { selected, name } = obj;
        if (this.currentLegendName !== name) {
          Object.keys(selected).forEach((key) => {
            selected[key] = key === name ? true : false;
          });
          this.currentLegendName = name;
        } else {
          if (selected[name] === false) {
            Object.keys(selected).forEach((key) => {
              selected[key] = true;
            });
            this.currentLegendName = "";
          }
        }
        option.legend.selected = selected;
        this.chartTwo.setOption(option);
      });
    },
  },
  watch: {
    offsetHeight() {
      document.getElementById("chartTwo").style.height =
        this.offsetHeight + "px";
      this.chartTwo = this.$echarts.init(document.getElementById("chartTwo"));
      if (Object.keys(this.info).length > 0) {
        this.getchartTwoData();
      }
    },
  },
  mounted() {},
  beforeDestroy() {
    this.chartTwo.dispose();
  },
};
</script>

<style lang="scss" scoped>
.circle {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  padding: 18%;
  margin-top: -18%;
  margin-left: -18%;
  border-radius: 50%;
  background-color: #eee;
}
.one-list-box {
  position: relative;
  left: 0;
  width: 100%;
  height: 30%;
  padding: 0 20px;
  overflow-y: auto;
}
.one-list {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 30px;
  list-style: none;
  li {
    position: relative;
    width: 50%;
    padding-top: 6px;
    padding-bottom: 6px;
    // padding-right: 20px;
    box-sizing: border-box;
    cursor: pointer;
    &.active {
      p {
        font-weight: bold;
        color: #504da6;
        i {
          color: #504da6;
        }
      }
    }
    p {
      padding-right: 10px;
      margin-bottom: 0;
      font-size: 14px;
      color: #7674a3;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      span {
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        margin-right: 10px;
      }
      i {
        line-height: 18px;
        font-style: normal;
      }
    }
  }
}
.no-data {
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  height: 40px;
  line-height: 40px;
  margin-top: -20px;
  text-align: center;
}
</style>
